/*
 * 登录页面组件 - Login Page Component
 * 提供用户登录、注册、第三方登录等认证功能
 * 支持响应式设计、防抖处理、键盘操作等增强功能
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Form, Input, Button, Card, message, Tabs, Divider, Space, Tooltip } from 'antd';
import { 
    UserOutlined, 
    LockOutlined, 
    MailOutlined, 
    EyeInvisibleOutlined, 
    EyeTwoTone,
    WechatOutlined,
    QqOutlined,
    GithubOutlined,
    AlipayOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'umi';
import './login.less';
import { login, register } from '@/services/User/api';
import { LoginParams, RegisterParams } from '@/models/user';

const { TabPane } = Tabs;

const LoginPage: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [registerLoading, setRegisterLoading] = useState<boolean>(false);
    const [activeTab, setActiveTab] = useState<string>('login');
    const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
    const [confirmPasswordVisible, setConfirmPasswordVisible] = useState<boolean>(false);
    const navigate = useNavigate();
    const [loginForm] = Form.useForm();
    const [registerForm] = Form.useForm();
    const submitTimeoutRef = useRef<NodeJS.Timeout | null>(null);

    const location = useLocation();
    const { redirect } = location.query || {};

    // 检查用户是否已登录，如果已登录则跳转到首页
    useEffect(() => {
        const account = localStorage.getItem('account');
        if (account) {
            navigate(redirect ? decodeURIComponent(redirect as string) : '/home');
        }
    }, []);

    // 清理定时器
    useEffect(() => {
        return () => {
            if (submitTimeoutRef.current) {
                clearTimeout(submitTimeoutRef.current);
            }
        };
    }, []);

    // 防抖处理函数
    const debounceSubmit = useCallback((submitFn: () => void, delay: number = 300) => {
        if (submitTimeoutRef.current) {
            clearTimeout(submitTimeoutRef.current);
        }
        submitTimeoutRef.current = setTimeout(submitFn, delay);
    }, []);

    // 第三方登录处理
    const handleThirdPartyLogin = useCallback((provider: string) => {
        message.info(`${provider}登录功能开发中...`);
        // TODO: 实现第三方登录逻辑
    }, []);

    // 键盘事件处理
    const handleKeyPress = useCallback((event: React.KeyboardEvent, formType: 'login' | 'register') => {
        if (event.key === 'Enter') {
            event.preventDefault();
            if (formType === 'login') {
                debounceSubmit(() => loginForm.submit());
            } else {
                debounceSubmit(() => registerForm.submit());
            }
        }
    }, [debounceSubmit, loginForm, registerForm]);

    const onLoginFinish = async (values: LoginParams) => {
        setLoading(true);
        try {
            const result = await login(values);
            
            // 使用优化后的API响应处理
            if (result.success && result.code === 200) {
                // 登录成功，保存用户信息和token
                if (result.data && result.data.data) {
                    const loginData = result.data.data;
                    localStorage.setItem('account', values.account);
                    localStorage.setItem('token', loginData.token);
                    localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo));
                    localStorage.setItem('userId', loginData.userInfo.id.toString());
                    message.success('登录成功');
                    navigate(redirect ? decodeURIComponent(redirect as string) : '/home');
                } else {
                    message.error('登录成功但未获取到用户信息');
                }
            } else {
                // 显示后端返回的错误消息
                message.error(result.message || '登录失败');
            }
        } catch (error) {
            message.error('登录失败，请稍后重试');
            console.error('登录错误:', error);
        } finally {
            setLoading(false);
        }
    };

    const onRegisterFinish = async (values: RegisterParams) => {
        setRegisterLoading(true);
        try {
            const result = await register(values);
            
            // 使用优化后的API响应处理
            if (result.success) {
                message.success('注册成功，请登录');
                setActiveTab('login');
                registerForm.resetFields();
            } else {
                // 显示后端返回的错误消息
                message.error(result.message || '注册失败');
            }
        } catch (error) {
            message.error('注册失败，请稍后重试');
            console.error('注册错误:', error);
        } finally {
            setRegisterLoading(false);
        }
    };

    return (
        <div className="login-container">
            {/* 浮动粒子装饰 */}
            <div className="floating-particles">
                <div className="particle"></div>
                <div className="particle"></div>
                <div className="particle"></div>
                <div className="particle"></div>
                <div className="particle"></div>
                <div className="particle"></div>
            </div>

            {/* 波浪蒙版装饰 */}
            <div className="wave-overlay">
                <div className="wave wave1"></div>
                <div className="wave wave2"></div>
            </div>

            <Card className="login-card">
                <Tabs 
                    activeKey={activeTab} 
                    onChange={setActiveTab}
                    centered
                    className="auth-tabs"
                >
                    <TabPane tab="登录" key="login">
                        <Form
                            form={loginForm}
                            name="loginForm"
                            layout="vertical"
                            onFinish={onLoginFinish}
                            initialValues={{ account: '', password: '' }}
                            className="auth-form"
                            onKeyPress={(e) => handleKeyPress(e, 'login')}
                        >
                            <Form.Item
                                name="account"
                                rules={[
                                    { required: true, message: '请输入账号' },
                                    { min: 3, message: '账号至少3个字符' },
                                    { max: 50, message: '账号不能超过50个字符' }
                                ]}
                            >
                                <Input 
                                    prefix={<UserOutlined />}
                                    placeholder="请输入账号" 
                                    autoComplete="account"
                                    size="large"
                                    maxLength={50}
                                />
                            </Form.Item>

                            <Form.Item
                                name="password"
                                rules={[
                                    { required: true, message: '请输入密码' },
                                    { min: 6, message: '密码至少6个字符' }
                                ]}
                            >
                                <Input.Password 
                                    prefix={<LockOutlined />}
                                    placeholder="请输入密码" 
                                    autoComplete="current-password"
                                    size="large"
                                    visibilityToggle={{
                                        visible: passwordVisible,
                                        onVisibleChange: setPasswordVisible,
                                    }}
                                    iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                />
                            </Form.Item>

                            <Form.Item>
                                <Button 
                                    type="primary" 
                                    htmlType="submit" 
                                    loading={loading} 
                                    block 
                                    size="large"
                                    className="auth-button"
                                    disabled={loading}
                                >
                                    {loading ? '登录中...' : '登录'}
                                </Button>
                            </Form.Item>

                            <Divider className="login-divider">
                                <span className="divider-text">或</span>
                            </Divider>

                            <div className="third-party-login">
                                <Space size="large" className="third-party-buttons">
                                    <Tooltip title="微信登录">
                                        <Button 
                                            shape="circle" 
                                            size="large" 
                                            className="third-party-btn wechat-btn"
                                            icon={<WechatOutlined />}
                                            onClick={() => handleThirdPartyLogin('微信')}
                                        />
                                    </Tooltip>
                                    <Tooltip title="QQ登录">
                                        <Button 
                                            shape="circle" 
                                            size="large" 
                                            className="third-party-btn qq-btn"
                                            icon={<QqOutlined />}
                                            onClick={() => handleThirdPartyLogin('QQ')}
                                        />
                                    </Tooltip>
                                    <Tooltip title="GitHub登录">
                                        <Button 
                                            shape="circle" 
                                            size="large" 
                                            className="third-party-btn github-btn"
                                            icon={<GithubOutlined />}
                                            onClick={() => handleThirdPartyLogin('GitHub')}
                                        />
                                    </Tooltip>
                                    <Tooltip title="支付宝登录">
                                        <Button 
                                            shape="circle" 
                                            size="large" 
                                            className="third-party-btn alipay-btn"
                                            icon={<AlipayOutlined />}
                                            onClick={() => handleThirdPartyLogin('支付宝')}
                                        />
                                    </Tooltip>
                                </Space>
                            </div>
                        </Form>
                    </TabPane>
                    
                    <TabPane tab="注册" key="register">
                        <Form
                            form={registerForm}
                            name="registerForm"
                            layout="vertical"
                            onFinish={onRegisterFinish}
                            initialValues={{ account: '', password: '', username: '' }}
                            className="auth-form"
                            onKeyPress={(e) => handleKeyPress(e, 'register')}
                        >
                            <Form.Item
                                name="account"
                                rules={[
                                    { required: true, message: '请输入账号' },
                                    { min: 3, message: '账号至少3个字符' },
                                    { max: 50, message: '账号不能超过50个字符' },
                                    { pattern: /^[a-zA-Z0-9_]+$/, message: '账号只能包含字母、数字和下划线' }
                                ]}
                            >
                                <Input 
                                    prefix={<UserOutlined />}
                                    placeholder="请输入账号（字母、数字、下划线）" 
                                    autoComplete="username"
                                    size="large"
                                    maxLength={50}
                                />
                            </Form.Item>

                            <Form.Item
                                name="username"
                                rules={[
                                    { required: true, message: '请输入用户名' },
                                    { min: 2, message: '用户名至少2个字符' },
                                    { max: 30, message: '用户名不能超过30个字符' }
                                ]}
                            >
                                <Input 
                                    prefix={<MailOutlined />}
                                    placeholder="请输入用户名" 
                                    size="large"
                                    maxLength={30}
                                />
                            </Form.Item>

                            <Form.Item
                                name="password"
                                rules={[
                                    { required: true, message: '请输入密码' },
                                    { min: 6, message: '密码至少6个字符' },
                                    { max: 50, message: '密码不能超过50个字符' },
                                    {
                                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/,
                                        message: '密码必须包含字母和数字'
                                    }
                                ]}
                                hasFeedback
                            >
                                <Input.Password 
                                    prefix={<LockOutlined />}
                                    placeholder="请输入密码（包含字母和数字）" 
                                    autoComplete="new-password"
                                    size="large"
                                    visibilityToggle={{
                                        visible: passwordVisible,
                                        onVisibleChange: setPasswordVisible,
                                    }}
                                    iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                />
                            </Form.Item>

                            <Form.Item
                                name="confirmPassword"
                                dependencies={['password']}
                                rules={[
                                    { required: true, message: '请确认密码' },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject(new Error('两次输入的密码不一致'));
                                        },
                                    }),
                                ]}
                                hasFeedback
                            >
                                <Input.Password 
                                    prefix={<LockOutlined />}
                                    placeholder="请确认密码" 
                                    autoComplete="new-password"
                                    size="large"
                                    visibilityToggle={{
                                        visible: confirmPasswordVisible,
                                        onVisibleChange: setConfirmPasswordVisible,
                                    }}
                                    iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                                />
                            </Form.Item>

                            <Form.Item>
                                <Button 
                                    type="primary" 
                                    htmlType="submit" 
                                    loading={registerLoading} 
                                    block 
                                    size="large"
                                    className="auth-button"
                                    disabled={registerLoading}
                                >
                                    {registerLoading ? '注册中...' : '注册'}
                                </Button>
                            </Form.Item>
                        </Form>
                    </TabPane>
                </Tabs>
            </Card>
        </div>
    );
};

export default LoginPage;